package com.stylefeng.guns.modular.system.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stylefeng.guns.common.persistence.dao.OrderBackRecordMapper;
import com.stylefeng.guns.common.persistence.model.OrderBackRecord;
import com.stylefeng.guns.common.persistence.model.TOrder;
import com.stylefeng.guns.core.util.DateUtil;
import com.stylefeng.guns.modular.system.service.IOrderBackRecordService;
import com.stylefeng.guns.modular.system.service.ITOrderService;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wengys123
 * @since 2018-03-13
 */
@Service
public class OrderBackRecordServiceImpl extends ServiceImpl<OrderBackRecordMapper, OrderBackRecord> implements IOrderBackRecordService {
    @Autowired
    OrderBackRecordMapper orderBackRecordMapper;
    @Autowired
    ITOrderService itOrderService;

    @Override
    @Transactional
    public void insertReceive(String ids, OrderBackRecord orderBackRecord) {
        this.insert(orderBackRecord);
        String[] id_arr= ids.split(",");
        for(String id:id_arr){
            TOrder tOrder=new TOrder();
            tOrder.setId(Integer.parseInt(id));
            tOrder.setOrder_back_receive_id(orderBackRecord.getId());
            tOrder.setReceiptStatus(1);
            itOrderService.updateById(tOrder);
        }
    }

    @Override
    @Transactional
    public void insertSend(String ids, OrderBackRecord orderBackRecord) {
        this.insert(orderBackRecord);
        String[] id_arr= ids.split(",");
        for(String id:id_arr){
            TOrder tOrder=new TOrder();
            tOrder.setId(Integer.parseInt(id));
            tOrder.setOrder_back_send_id(orderBackRecord.getId());
            tOrder.setReceiptStatus(2);
            itOrderService.updateById(tOrder);
        }
    }

    @Override
    @Transactional
    public void insertReceiveAndSend(String ids, OrderBackRecord orderBackRecord) {
        this.insert(orderBackRecord);
        String[] id_arr= ids.split(",");
        for(String id:id_arr){
            TOrder tOrder=new TOrder();
            tOrder.setId(Integer.parseInt(id));
            tOrder.setOrder_back_receive_id(orderBackRecord.getId());
            tOrder.setOrder_back_send_id(orderBackRecord.getId());
            tOrder.setReceiptStatus(2);
            itOrderService.updateById(tOrder);
        }
    }

    @Override
    public List<Map<String, Object>> selectOrderBackRecordList(Page<Map<String, Object>> page, Map m) {
        return orderBackRecordMapper.selectOrderBackRecordList(page,m);
    }

    @Override
    public void export(String filepath, String returnpath, String id) {
        OrderBackRecord orderBackRecord = orderBackRecordMapper.selectById(id);

        Wrapper<TOrder> wrapper1 = new EntityWrapper<>();
        wrapper1 = wrapper1.where("order_back_receive_id={0}", id).or("order_back_send_id={0}", id);
        List<TOrder> tOrderList = itOrderService.selectList(wrapper1);

        try {
            File file = new File(filepath);
            if (!file.exists()) {
                if (!file.createNewFile()) {
                    throw new IOException("文件创建失败");
                }
            }
            //创建HSSFWorkbook对象(excel的文档对象)
            HSSFWorkbook wb = new HSSFWorkbook();
            //建立新的sheet对象（excel的表单）
            HSSFSheet sheet = wb.createSheet("Sheet1");
            //在sheet里创建第一行，参数为行索引(excel的行)，可以是0～65535之间的任何一个
            HSSFRow row1 = sheet.createRow(0);
            //创建单元格（excel的单元格，参数为列索引，可以是0～255之间的任何一个
            HSSFCell cell = row1.createCell(0);
            //设置单元格内容
            //     cell.setCellValue(" );
            //合并单元格CellRangeAddress构造参数依次表示起始行，截至行，起始列， 截至列
            //     sheet.addMergedRegion(new CellRangeAddress(0,0,0,3));
            //在sheet里创建第二行
            HSSFRow row2 = sheet.createRow(0);
            //创建单元格并设置单元格内容
            row2.createCell(0).setCellValue("运单号");
            row2.createCell(1).setCellValue("发货人");
            row2.createCell(2).setCellValue("品名");
            row2.createCell(3).setCellValue("件数");
            row2.createCell(4).setCellValue("重量");
            row2.createCell(5).setCellValue("立方");
            row2.createCell(6).setCellValue("收货人");
            row2.createCell(7).setCellValue("收货电话");
            row2.createCell(8).setCellValue("回单要求");
            row2.createCell(9).setCellValue("接收方");
            row2.createCell(10).setCellValue("回寄方式");
            row2.createCell(11).setCellValue("备注");
            row2.createCell(12).setCellValue("操作时间");


            for (int i = 0; i < tOrderList.size(); i++) {
                HSSFRow row3 = sheet.createRow(i + 1);
                row3.createCell(0).setCellValue(tOrderList.get(i).getOriginal_num()==null?"":tOrderList.get(i).getOriginal_num().toString());
                row3.createCell(1).setCellValue(tOrderList.get(i).getSendDeptName()==null?"":tOrderList.get(i).getSendDeptName().toString());
                row3.createCell(2).setCellValue(tOrderList.get(i).getGoodsName()==null?"":tOrderList.get(i).getGoodsName().toString());
                row3.createCell(3).setCellValue(tOrderList.get(i).getGoodsPiece()==null?"":tOrderList.get(i).getGoodsPiece().toString());
                row3.createCell(4).setCellValue(tOrderList.get(i).getGoodsWeight()==null?"":tOrderList.get(i).getGoodsWeight().toString());
                row3.createCell(5).setCellValue(tOrderList.get(i).getGoodsVolume()==null?"":tOrderList.get(i).getGoodsVolume().toString());
                row3.createCell(6).setCellValue(tOrderList.get(i).getConsignee()==null?"":tOrderList.get(i).getConsignee().toString());
                row3.createCell(7).setCellValue(tOrderList.get(i).getReceivingPhone()==null?"":tOrderList.get(i).getReceivingPhone().toString());
                row3.createCell(8).setCellValue(tOrderList.get(i).getReceipt()==null?"":tOrderList.get(i).getReceipt().toString());
                row3.createCell(9).setCellValue(orderBackRecord.getReceiver()==null?"":orderBackRecord.getReceiver().toString());
                String type="";
                if(orderBackRecord.getProcessMethod()!=null){
                    if("1".equals(orderBackRecord.getProcessMethod())){
                        type="邮寄";
                    }else if("2".equals(orderBackRecord.getProcessMethod())){
                        type="司机带回";
                    }else{
                        type="其他";
                    }
                }
                row3.createCell(10).setCellValue(type);
                row3.createCell(11).setCellValue(orderBackRecord.getRemark()==null?"":orderBackRecord.getRemark().toString());
                row3.createCell(12).setCellValue(DateUtil.formatDate(orderBackRecord.getCreateTime(),"yyyy-MM-dd HH:mm:ss"));
            }
            FileOutputStream fout = new FileOutputStream(filepath);
            wb.write(fout);
            fout.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
